const sharp = require('sharp');
const plist = require('plist');
const path = require('path');
const fs = require('fs');

// 配置路径和参数
const inputPath = 'dice_hd_preview.png';
const outputDir = 'output';
const tileWidth = 70;
const tileHeight = 70;

if (!fs.existsSync(outputDir)) {
    fs.mkdirSync(outputDir);
};

// 处理图像切分
const processTiles = async () => {
    try {
        const { width, height } = await sharp(inputPath).metadata();

        let x = 0;
        let y = 0;
        let index = 0;
        const plistData = {
            frames: {},
            metadata: {
                format: 2,
                size: { width, height },
                scale: "1"
            }
        };

        // 遍历图像并切分
        while (y < height) {
            x = 0;
            while (x < width) {
                const extractWidth = Math.min(tileWidth, width - x);
                const extractHeight = Math.min(tileHeight, height - y);

                const tileName = `tile_${index}.png`;
                await sharp(inputPath)
                    .extract({ left: x, top: y, width: extractWidth, height: extractHeight })
                    .toFile(path.join(outputDir, tileName));
                console.log(`Created ${tileName}`);
                
                plistData.frames[tileName] = {
                    frame: { x, y, w: extractWidth, h: extractHeight },
                    rotated: false,
                    trimmed: false,
                    spriteSourceSize: { x: 0, y: 0, w: extractWidth, h: extractHeight },
                    sourceSize: { w: extractWidth, h: extractHeight }
                };
                index++;
                x += tileWidth;
            }
            y += tileHeight;
        }

        // 生成 plist 文件
        fs.writeFileSync(path.join(outputDir, 'output.plist'), plist.build(plistData));
        console.log('Plist file created');
    } catch (err) {
        console.error('Error processing image:', err);
    }
};

processTiles();
